package captcha;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class Captcha {
	Map<Coordinate,Color> monoBitMap = new HashMap<Coordinate,Color>();
	public Captcha(Map<Coordinate,Color> monoBitMap) {
		super();
		this.monoBitMap = monoBitMap;
	}
	public void PreWork() {
		cutToRelevant();
	}
	/**
	 * Schneidet das Bild auf den Teil zu, in dem Informationen stecken
	 */
	public void cutToRelevant() {
		Set<Integer> rows = new HashSet<Integer>();
		Set<Integer> cols = new HashSet<Integer>();
		for (Entry<Coordinate,Color> e: monoBitMap.entrySet()) {
			if (e.getValue().toBoolean()) {
				if (!rows.contains(e.getKey().x)) rows.add(e.getKey().x);
				if (!cols.contains(e.getKey().y)) cols.add(e.getKey().y);
			}
		}
		Integer minRow = null;
		Integer maxRow = null;
		for (Integer i:rows) {
			if (minRow == null || i < minRow)
				minRow = i;
			if (maxRow == null || i > maxRow)
				maxRow = i;
		}
		Integer minCol = null;
		Integer maxCol = null;
		for (Integer i:cols) {
			if (minCol == null || i < minCol)
				minCol = i;
			if (maxCol == null || i > maxCol)
				maxCol = i;
		}

		Map<Coordinate,Color> newMonoBitMap = new HashMap<Coordinate,Color>();
		for (Entry<Coordinate,Color> e: monoBitMap.entrySet()) {
			if (e.getKey().x >= minRow && e.getKey().y <= maxRow &&
					e.getKey().y >= minCol && e.getKey().y <= maxCol) {
				newMonoBitMap.put(e.getKey(), e.getValue());
			}
		}
		monoBitMap = newMonoBitMap;
	}
}
